package net.p2pcdn.task;

import net.p2pcdn.common.Date2StringConverter;
import net.p2pcdn.core.order.domain.ContractDO;
import net.p2pcdn.core.order.domain.ExpiringContract;
import net.p2pcdn.core.order.domain.WillEffectiveContract;
import net.p2pcdn.core.order.repository.ContractRepository;
import net.p2pcdn.core.order.repository.ExpiringContractRepository;
import net.p2pcdn.core.order.repository.WillEffectiveContractRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 处理即将时效的合约
 *
 * @author zx
 */
@Component
public class WillEffectiveContractExecutor {
    @Resource
    private WillEffectiveContractRepository willEffectiveContractRepository;
    @Autowired
    private ContractRepository contractRepository;

    @Scheduled(cron = "0 0 0 */1 * ?")
    public void execute(){
        Map<String,Object> params = new HashMap<>(5);
        Date from = Date2StringConverter.getDateOfStartTime();
        Date to  = Date2StringConverter.getDateOfEndTime();
        params.put("from",from);
        params.put("to",to);
        List<ContractDO> contracts = null;
        do{
            contracts  = contractRepository.queryContractsThatBecomeEffective(params);
            List<WillEffectiveContract> willContracts = new ArrayList<>();
            contracts.forEach(item -> willContracts.add(new WillEffectiveContract(item)));
            if(willContracts.size() > 0){
                willEffectiveContractRepository.batchInsert(willContracts);
            }
        }
        while(contracts.size() > 0);
    }


}
